package com.chenxi;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/*
int getWaitQueueLength(Condition con)方法的作用是返回等待与此锁定相关的给定Condition的线程数。就是有多少个指定的Condition实例在等待此锁定。
 */

public class MyWaitQuere {

    public ReentrantLock lock = new ReentrantLock();
    public Condition con = lock.newCondition();

    public void waitMethod(){
        try{
            lock.lock();
            System.out.println("⭐线程 "+ Thread.currentThread().getName() + "进入等待");
            con.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void signalMethod(){
        try{
            lock.lock();
            System.out.println("有 " + lock.getWaitQueueLength(con) + "个线程正在等待con");
            con.signal();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyWaitQuere myWaitQuere = new MyWaitQuere();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                myWaitQuere.waitMethod();
            }
        };
        Thread[] threads = new Thread[10];
        for(int i = 0;i< 10;i++){
            threads[i] = new Thread(runnable);
        }
        Arrays.stream(threads).forEach(thread -> thread.start());
        Thread.sleep(2000);
        myWaitQuere.signalMethod();
    }
}
